<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统 - 图书管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .header h1 {
            font-size: 20px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .nav {
            background: white;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            gap: 20px;
        }
        
        .nav-item {
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .nav-item.active {
            background: #667eea;
            color: white;
        }
        
        .nav-item:hover:not(.active) {
            background: #f0f0f0;
        }
        
        .container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .toolbar {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .search-form {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .form-group label {
            font-size: 14px;
            color: #666;
        }
        
        .form-group input, .form-group select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th, .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }
        
        .table tr:hover {
            background: #f8f9fa;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }
        
        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 8px;
            width: 500px;
            max-width: 90%;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
        }
        
        .close {
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        
        .modal-body {
            margin-bottom: 20px;
        }
        
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }
        
        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 5px;
        }
        
        .pagination button:hover {
            background: #f0f0f0;
        }
        
        .pagination button.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>图书管理系统</h1>
        <div class="user-info">
            <span id="username"></span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>
    
    <div class="nav">
        <div id="nav-book" class="nav-item active">图书管理</div>
        <div id="nav-statistics" class="nav-item">统计图表</div>
    </div>
    
    <div class="container">
        <!-- 图书管理页面 -->
        <div id="bookPage">
            <div class="toolbar">
                <div class="search-form">
                    <div class="form-group">
                        <label>图书名称</label>
                        <input type="text" id="searchBookName" placeholder="请输入图书名称">
                    </div>
                    <div class="form-group">
                        <label>图书类别</label>
                        <select id="searchCategory">
                            <option value="">全部类别</option>
                            <option value="计算机技术">计算机技术</option>
                            <option value="文学小说">文学小说</option>
                            <option value="科幻小说">科幻小说</option>
                            <option value="科普读物">科普读物</option>
                            <option value="历史">历史</option>
                            <option value="经济管理">经济管理</option>
                            <option value="心理学">心理学</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>作者</label>
                        <input type="text" id="searchAuthor" placeholder="请输入作者">
                    </div>
                    <button id="searchBtn" class="btn btn-primary">搜索</button>
                    <button id="addBtn" class="btn btn-success">新增图书</button>
                </div>
            </div>
            
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>图书名称</th>
                            <th>类别</th>
                            <th>价格</th>
                            <th>作者</th>
                            <th>出版社</th>
                            <th>库存</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="bookTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <div class="pagination" id="pagination">
                <!-- 分页将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <!-- 统计图表页面 -->
        <div id="statisticsPage" style="display: none;">
            <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <h3>图书类别统计</h3>
                <div id="categoryChart" style="height: 400px;"></div>
            </div>
            <div style="background: white; padding: 20px; border-radius: 8px;">
                <h3>价格区间统计</h3>
                <div id="priceChart" style="height: 400px;"></div>
            </div>
        </div>
    </div>
    
    <!-- 新增/编辑图书模态框 -->
    <div id="bookModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="modalTitle">新增图书</h3>
                <span id="closeModalBtn" class="close">&times;</span>
            </div>
            <div class="modal-body">
                <form id="bookForm">
                    <input type="hidden" id="bookId">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label>图书编号</label>
                            <input type="text" id="bookCode" required>
                        </div>
                        <div class="form-group">
                            <label>图书名称</label>
                            <input type="text" id="bookName" required>
                        </div>
                        <div class="form-group">
                            <label>图书类别</label>
                            <select id="category" required>
                                <option value="">请选择类别</option>
                                <option value="计算机技术">计算机技术</option>
                                <option value="文学小说">文学小说</option>
                                <option value="科幻小说">科幻小说</option>
                                <option value="科普读物">科普读物</option>
                                <option value="历史">历史</option>
                                <option value="经济管理">经济管理</option>
                                <option value="心理学">心理学</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>价格</label>
                            <input type="number" id="price" step="0.01" required>
                        </div>
                        <div class="form-group">
                            <label>作者</label>
                            <input type="text" id="author">
                        </div>
                        <div class="form-group">
                            <label>出版社</label>
                            <input type="text" id="publisher">
                        </div>
                        <div class="form-group">
                            <label>ISBN</label>
                            <input type="text" id="isbn">
                        </div>
                        <div class="form-group">
                            <label>库存</label>
                            <input type="number" id="stock" value="0">
                        </div>
                    </div>
                    <div class="form-group" style="margin-top: 15px;">
                        <label>描述</label>
                        <textarea id="description" rows="3" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="cancelBtn" class="btn">取消</button>
                <button id="saveBtn" class="btn btn-primary">保存</button>
            </div>
        </div>
    </div>

    <script src="echarts.min.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let categoryChart = null;
        let priceChart = null;
        
        // 页面加载时检查登录状态
        window.onload = function() {
            checkAuth();
            loadBooks();
            setupEventListeners();
        };
        
        // 统一设置事件监听
        function setupEventListeners() {
            // 导航
            document.getElementById('nav-book').addEventListener('click', () => showPage('book'));
            document.getElementById('nav-statistics').addEventListener('click', () => showPage('statistics'));
            
            // 工具栏按钮
            document.querySelector('.logout-btn').addEventListener('click', logout);
            document.getElementById('searchBtn').addEventListener('click', searchBooks);
            document.getElementById('addBtn').addEventListener('click', showAddModal);

            // 模态框按钮
            document.getElementById('closeModalBtn').addEventListener('click', closeModal);
            document.getElementById('cancelBtn').addEventListener('click', closeModal);
            document.getElementById('saveBtn').addEventListener('click', saveBook);
        }
        
        // 检查登录状态
        function checkAuth() {
            const token = sessionStorage.getItem('token');
            const username = sessionStorage.getItem('username');
            
            if (!token || !username) {
                window.location.href = '/login.html';
                return;
            }
            
            document.getElementById('username').textContent = username;
        }
        
        // 退出登录
        function logout() {
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('username');
            window.location.href = '/login.html';
        }
        
        // 显示页面
        function showPage(page) {
            const navBook = document.getElementById('nav-book');
            const navStatistics = document.getElementById('nav-statistics');
            const bookPage = document.getElementById('bookPage');
            const statisticsPage = document.getElementById('statisticsPage');

            if (page === 'book') {
                bookPage.style.display = 'block';
                statisticsPage.style.display = 'none';
                navBook.classList.add('active');
                navStatistics.classList.remove('active');
            } else if (page === 'statistics') {
                bookPage.style.display = 'none';
                statisticsPage.style.display = 'block';
                navBook.classList.remove('active');
                navStatistics.classList.add('active');
                loadStatistics();
            }
        }
        
        // 加载图书列表
        function loadBooks() {
            const searchData = {
                bookName: document.getElementById('searchBookName').value,
                category: document.getElementById('searchCategory').value,
                author: document.getElementById('searchAuthor').value,
                pageNum: currentPage,
                pageSize: pageSize
            };
            
            fetch('/api/book/page', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                },
                body: JSON.stringify(searchData)
            })
            .then(response => {
                if (response.status === 401) {
                    logout();
                    return;
                }
                return response.json();
            })
            .then(data => {
                if (data && data.code === 200) {
                    renderBookTable(data.data.records);
                    renderPagination(data.data.total);
                }
            })
            .catch(error => {
                console.error('加载图书列表失败:', error);
            });
        }
        
        // 渲染图书表格
        function renderBookTable(books) {
            const tbody = document.getElementById('bookTableBody');
            tbody.innerHTML = '';
            
            books.forEach(book => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${book.bookCode}</td>
                    <td>${book.bookName}</td>
                    <td>${book.category}</td>
                    <td>￥${book.price}</td>
                    <td>${book.author || '-'}</td>
                    <td>${book.publisher || '-'}</td>
                    <td>${book.stock}</td>
                    <td>${book.status === 1 ? '上架' : '下架'}</td>
                    <td>
                        <button class="btn btn-primary" onclick="editBook(${book.id})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteBook(${book.id})">删除</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }
        
        // 渲染分页
        function renderPagination(total) {
            totalPages = Math.ceil(total / pageSize);
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            // 上一页
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadBooks();
                }
            };
            pagination.appendChild(prevBtn);
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                pageBtn.className = currentPage === i ? 'active' : '';
                pageBtn.onclick = () => {
                    currentPage = i;
                    loadBooks();
                };
                pagination.appendChild(pageBtn);
            }
            
            // 下一页
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    loadBooks();
                }
            };
            pagination.appendChild(nextBtn);
        }
        
        // 搜索图书
        function searchBooks() {
            currentPage = 1;
            loadBooks();
        }
        
        // 显示新增模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '新增图书';
            document.getElementById('bookForm').reset();
            document.getElementById('bookId').value = '';
            document.getElementById('bookModal').style.display = 'block';
        }
        
        // 编辑图书
        function editBook(id) {
            fetch(`/api/book/${id}`, {
                headers: {
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const book = data.data;
                    document.getElementById('modalTitle').textContent = '编辑图书';
                    document.getElementById('bookId').value = book.id;
                    document.getElementById('bookCode').value = book.bookCode;
                    document.getElementById('bookName').value = book.bookName;
                    document.getElementById('category').value = book.category;
                    document.getElementById('price').value = book.price;
                    document.getElementById('author').value = book.author || '';
                    document.getElementById('publisher').value = book.publisher || '';
                    document.getElementById('isbn').value = book.isbn || '';
                    document.getElementById('stock').value = book.stock;
                    document.getElementById('description').value = book.description || '';
                    document.getElementById('bookModal').style.display = 'block';
                }
            });
        }
        
        // 保存图书
        function saveBook() {
            const bookId = document.getElementById('bookId').value;
            const bookData = {
                bookCode: document.getElementById('bookCode').value,
                bookName: document.getElementById('bookName').value,
                category: document.getElementById('category').value,
                price: parseFloat(document.getElementById('price').value),
                author: document.getElementById('author').value,
                publisher: document.getElementById('publisher').value,
                isbn: document.getElementById('isbn').value,
                stock: parseInt(document.getElementById('stock').value),
                description: document.getElementById('description').value,
                status: 1
            };
            
            const url = bookId ? '/api/book' : '/api/book';
            const method = bookId ? 'PUT' : 'POST';
            
            if (bookId) {
                bookData.id = parseInt(bookId);
            }
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                },
                body: JSON.stringify(bookData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    closeModal();
                    loadBooks();
                    alert(bookId ? '编辑成功' : '新增成功');
                } else {
                    alert(data.message);
                }
            });
        }
        
        // 删除图书
        function deleteBook(id) {
            if (confirm('确定要删除这本书吗？')) {
                fetch(`/api/book/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        loadBooks();
                        alert('删除成功');
                    } else {
                        alert(data.message);
                    }
                });
            }
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('bookModal').style.display = 'none';
        }
        
        // 加载统计数据
        function loadStatistics() {
            loadCategoryStatistics();
            loadPriceStatistics();
        }
        
        // 加载类别统计
        function loadCategoryStatistics() {
            fetch('/api/book/statistics/category', {
                headers: {
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取类别统计数据失败: ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    renderCategoryChart(data.data);
                } else {
                    console.error('渲染类别图表失败:', data.message);
                }
            })
            .catch(error => {
                console.error('获取类别统计数据时发生网络错误:', error);
            });
        }
        
        // 加载价格统计
        function loadPriceStatistics() {
            fetch('/api/book/statistics/price-range', {
                headers: {
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token')
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取价格统计数据失败: ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    renderPriceChart(data.data);
                } else {
                    console.error('渲染价格图表失败:', data.message);
                }
            })
            .catch(error => {
                console.error('获取价格统计数据时发生网络错误:', error);
            });
        }
        
        // 渲染类别图表
        function renderCategoryChart(data) {
            if (!categoryChart) {
                categoryChart = echarts.init(document.getElementById('categoryChart'));
            }
            
            const option = {
                title: {
                    text: '图书类别分布',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: '图书类别',
                        type: 'pie',
                        radius: '50%',
                        data: data.map(item => ({
                            name: item.name,
                            value: item.value
                        })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            
            categoryChart.setOption(option);
        }
        
        // 渲染价格图表
        function renderPriceChart(data) {
            if (!priceChart) {
                priceChart = echarts.init(document.getElementById('priceChart'));
            }
            
            const option = {
                title: {
                    text: '价格区间分布',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.name)
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '图书数量',
                        type: 'bar',
                        data: data.map(item => item.value),
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#83bff6' },
                                { offset: 0.5, color: '#188df0' },
                                { offset: 1, color: '#188df0' }
                            ])
                        }
                    }
                ]
            };
            
            priceChart.setOption(option);
        }
        
        // 窗口大小改变时重新调整图表
        window.addEventListener('resize', function() {
            if (categoryChart) {
                categoryChart.resize();
            }
            if (priceChart) {
                priceChart.resize();
            }
        });
    </script>
</body>
</html> 